import os
import sys

if len(sys.argv) < 2:
	print("error: at least 1 arguments are required. ", file=sys.stderr)
	print("Usage: ansi_to_utf_8 file1 [file2 ...]")


for i in range(1, len(sys.argv)):
	if not os.path.exists(sys.argv[i]):
		print(f"\033[95mwarning:\033[0m file \"{sys.argv[i]}\" does not exist. ", file=sys.stderr)
		continue

	try:
		with open(sys.argv[i], 'r') as f:
			content = f.read()
	except Exception as e:
		print(f"\033[95mwarning:\033[0m opening {sys.argv[i]} failed! {e}", file=sys.stderr)
		print(f"\t It seems that {sys.argv[i]} is a utf-8 encoding file. ", file=sys.stderr)
		continue

	try:
		with open(sys.argv[i], 'w', encoding="utf-8") as f:
			f.write(content)
	except Exception as e:
		print(f"\033[91merror:\033[0m writing {sys.argv[i]} failed! {e}", file=sys.stderr)
		exit(1)

	print(f"successfully converted {sys.argv[i]} to utf-8! ")
